import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
    public static void main(String[] args) {
        new  ChatClient();
    }
    public ChatClient() {
    try{
        Socket socket = new Socket("localhost", 9901);
        System.out.println("请输入您的姓名：");
        Scanner sc=new Scanner(System.in);
        String name=sc.nextLine();
        OutputStream os=socket.getOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(os);
        oos.writeObject(name);
        InputStream is=socket.getInputStream();
        ObjectInputStream ois=new ObjectInputStream(is);
        try {
            System.out.println(ois.readObject());
            new Thread(){
                @Override
                public void run() {
                while (true){
                    try {
                        String msg=sc.nextLine();
                        oos.writeObject(msg);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                }
            }.start();
            new Thread(){
                @Override
                public void run() {
                    while (true){
                        try {
                            String msg=(String) ois.readObject();
                            System.out.println(msg);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }.start();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    }
 }
